package com.example.xjtuse_pc.mobilesafe.LostGuid;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.xjtuse_pc.mobilesafe.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PhontNumberActivity extends Activity {
    private ListView select_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phont_number);
        select_phone= (ListView) findViewById(R.id.select_phone);
        final List<Map<String,String>> data=getContentInfo();
        select_phone.setAdapter(new SimpleAdapter(this,
                data, R.layout.contact_item_view,
                new String[]{"name","phone"},
                new int[]{R.id.tv_name,R.id.tv_number}));
    select_phone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String phone =data.get(i).get("phone");
            Intent data=new Intent();
            data.putExtra("phone",phone);
            setResult(0,data);
            finish();

        }
    });
    }
    /**
     * 手机号码
     */
    private List<Map<String,String>> getContentInfo() {
        List<Map<String, String>> list  = new ArrayList<Map<String,String>>();
        ContentResolver resolver=getContentResolver();
        Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");
        Uri uriData=Uri.parse("content://com.android.contacts/data");
        Cursor cursor=resolver.query(uri, new String[]{"contact_id"}, null, null, null);
        while (cursor.moveToNext()){
            Log.i("join","------------------");
            String id=cursor.getString(0);
            Log.i("join",id);
            if(id!=null){
                Map<String,String> map=new HashMap<String, String>();
               Cursor curate= resolver.query(uriData, new String[]{"data1", "mimetype"}, "contact_id=?", new String[]{id}, null);
               while (curate.moveToNext()){
                   if(curate.getString(1).equals("vnd.android.cursor.item/phone_v2")){
                    //联系人号码
                       Log.i("join",curate.getString(0));
                       map.put("phone",curate.getString(0));
                   }else  if(curate.getString(1).equals("vnd.android.cursor.item/name")){
                   //联系人名字
                       Log.i("join",curate.getString(0));
                        map.put("name",curate.getString(0));
                   }
               }
                list.add(map);
            }
        }
    return list;
    }

}
